<template>
    <div class="userInfo">
        <el-form ref="AddCarRef" :rules="rules" style="max-width: 600px" :model="orderInfo" label-width="auto" class="demo-ruleForm"
            :size="formSize" status-icon>
            <el-form-item label="用户id" prop="userId">
                <el-input v-model="orderInfo.userId" placeholder="请输入用户id" />
            </el-form-item>
            <el-form-item label="车辆id" prop="carId">
                <el-input v-model="orderInfo.carId" placeholder="请输入车辆id" />
            </el-form-item>
            <el-form-item label="押金" prop="deposit">
                <el-input v-model="orderInfo.deposit" placeholder="请输入押金"/>
            </el-form-item>
            <el-form-item label="租金/天" prop="rentPrice">
                <el-input v-model="orderInfo.rentPrice" placeholder="请输入租金"/>
            </el-form-item>
            <el-form-item label="天数" prop="days">
                <el-input v-model="orderInfo.days" placeholder="请输入天数"/>
            </el-form-item>
            <el-form-item style="display: flex; justify-content: center;" >
                        <el-button type="primary" @click="submitForm(AddCarRef)">保存</el-button>
                        <el-button @click="resetForm(AddCarRef)">重置</el-button>
                    </el-form-item>
        </el-form>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue'
import type { ComponentSize, FormInstance, FormRules,} from 'element-plus'
import { getOrderById, updateOrder } from '@/api'
import { ElMessage } from 'element-plus'
import { useRoute } from 'vue-router';

const formSize = ref<ComponentSize>('default')
const AddCarRef = ref<FormInstance>()
let orderInfo = reactive({
    id: '',
    userId: '',
    carId: '',
    deposit: '',
    rentPrice: '',
    days: '',
    total: '',
    createTime: ''
})

const id = ref()

// 在组件挂载时初始化数据
onMounted(() => {
    const route = useRoute();
    // 获取查询参数 id存在则是编辑 反之新增
    id.value = route.query.id as string | undefined;
    if(id.value){
        // 发送请求 根据id查数据
        getOrderById(id.value).then((resp: { data: any; }) => {
            let data = resp.data;
            if (data.code == '50041') {
                Object.assign(orderInfo, data.data);
            } else {
                ElMessage({
                    message: data.message,
                    type: 'error'
                });
            }
        });
    }
});

const rules = reactive<FormRules>({
    userId: [{ required: true, message: '请输入用户id', trigger: 'blur' }],
    carId: [{ required: true, message: '请输入车辆id', trigger: 'blur' }],
    deposit: [{ required: true, message: '请输入押金', trigger: 'blur' }],
    rentPrice: [{ required: true, message: '请输入租金', trigger: 'blur' }],
    days: [{ required: true, message: '请输入天数', trigger: 'blur' }],
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if(id.value){
                const deposit = parseFloat(orderInfo.deposit);
                const rentPrice = parseFloat(orderInfo.rentPrice);
                const days = parseFloat(orderInfo.days);
                orderInfo.total = (deposit + rentPrice * days).toString();
                updateOrder(orderInfo).then((resp: { data: any; }) => {
                    let data = resp.data;
                    if (data.code == '50031') {
                        ElMessage({
                            message: data.message,
                            type: 'success'
                        });
                        // 发送消息给父窗口，告知要改变页面
                        window.parent.postMessage({ action: 'changePage', url: '/#/order/list' }, '*');
                    } else {
                        ElMessage({
                            message: data.message,
                            type: 'error'
                        });
                    }
                });
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))
</script>

<style scoped>
.userInfo {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    padding: 20px;
    box-sizing: border-box;
}
</style>